package com.ay;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

/**
 * https://blog.csdn.net/m0_37729339/article/details/81504733?utm_source=blogxgwz5
 */
public class FormEditor
{

	public FormEditor()
	{

	}

	public void execute(String src, String dest, HashMap<String, Object> data)
	{
		FileInputStream in = null;
		ByteArrayOutputStream output = null;
		try
		{
			/**
			 * 1、使用iTextAsian.jar中的字体 BaseFont.createFont("STSong-Light",
			 * "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED); 2、使用Windows系统字体(TrueType)
			 * BaseFont.createFont("C:/WINDOWS/Fonts/SIMYOU.TTF",
			 * BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); 3、使用资源字体(ClassPath)
			 * BaseFont.createFont("/SIMYOU.TTF",
			 * BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
			 * 
			 * 直接用BaseFont，simhei字体弄BaseFont无效，android 系统字体可以
			 */
			BaseFont baseFont = BaseFont.createFont("assets/fonts/DroidSansFallback.ttf", BaseFont.IDENTITY_H,
					BaseFont.NOT_EMBEDDED);
			// BaseFont baseFont =
			// BaseFont.createFont("assets/fonts/simhei.ttf",
			// BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
			in = new FileInputStream(src);
			byte[] pdfBytes = new byte[in.available()];
			in.read(pdfBytes);

			PdfReader reader = new PdfReader(pdfBytes);
			output = new ByteArrayOutputStream();
			PdfStamper stamp = new PdfStamper(reader, output);
			AcroFields form = stamp.getAcroFields();

			// 获取form表单的表单名称--》测试看能不能获得pdf文件中的Form表单的名称
			java.util.Iterator<String> it = data.keySet().iterator();
			while (it.hasNext())
			{
				String key = (String) it.next();
				String value = (String) data.get(key);
				if (key.equals("signed_image"))
				{
					// ByteArrayOutputStream baos = new ByteArrayOutputStream();
					// Bitmap bitmap = (Bitmap) data.get(key);
					// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
					insertImage(stamp, form, value.toString());
					// form.removeField(key);//之所以要删除因为它会盖住插入的图片，这个需要确认是不是定义的编辑域方式不对
				} else
				{
					form.setFieldProperty(key, "textfont", baseFont, null);// 设置字体
					// form.setFieldProperty(key, "textsize", 16, null); //
					// 设置字体大小.没作用
					form.setField(key, value.toString());
				}
			}
			stamp.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
			stamp.close();
			in.close();
			toPdf(dest, output);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 生成新的PDF文件
	 *
	 * @param fileName
	 * @throws DocumentException
	 * @throws IOException
	 * @user : caoxu-yiyang@qq.com
	 * @date : 2016年11月9日
	 */
	public void toPdf(String fileName, ByteArrayOutputStream output) throws DocumentException, IOException
	{
		FileOutputStream fileOutputStream = null;
		try
		{
			fileOutputStream = new FileOutputStream(fileName);
			fileOutputStream.write(output.toByteArray());
			fileOutputStream.flush();
		} catch (IOException e)
		{
			throw e;
		} finally
		{
			if (fileOutputStream != null)
			{
				fileOutputStream.close();
			}
			output.close();
		}
	}

	/**
	 * 插入图片
	 *
	 * @param ps
	 * @param s
	 * @author WangMeng
	 * @date 2016年6月16日
	 */
	public static void insertImage(PdfStamper ps, AcroFields s, String imagePath)
	{
		try
		{
			List<AcroFields.FieldPosition> list = s.getFieldPositions("signed_image");
			Rectangle signRect = list.get(0).position;
			int pageNo = s.getFieldPositions("signed_image").get(0).page;
			Image image = Image.getInstance(imagePath);
			PdfContentByte over = ps.getOverContent(pageNo);
			float x = signRect.getLeft();
			float y = signRect.getBottom();
			image.scaleToFit(signRect.getWidth(), signRect.getHeight());
			image.setAbsolutePosition(x, y);
			over.addImage(image);
		} catch (Exception e)
		{
			e.printStackTrace();
		}

	}

	/**
	 * 创建Chunk
	 *
	 * @return
	 * @author WangMeng
	 * @date 2016年6月16日
	 */
	public static Chunk CreateChunk()
	{
		BaseFont bfChinese;
		Chunk chunk = null;
		try
		{
			bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
			Font fontChinese = new Font(bfChinese, 10 * 4 / 3);
			chunk = new Chunk("张三", fontChinese);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return chunk;
	}
}
